const formatDate = (date, fmt) => {
    if (date === undefined || date === null || date === '') return ''

    let o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日期
        'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 12小时制
        'H+': date.getHours(), // 24小时制
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        'S': date.getMilliseconds() // 毫秒
    }
    let week = {
        '0': '\u65e5',
        '1': '\u4e00',
        '2': '\u4e8c',
        '3': '\u4e09',
        '4': '\u56db',
        '5': '\u4e94',
        '6': '\u516d'
    }
    // 匹配y，匹配成功，用date中的year替换fmt中的y
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    // 匹配周 EE对应周一……；EEE对应星期一……
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '\u661f\u671f' : '\u5468') : '') + week[date.getDay() + ''])
    }
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + ''
            fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : ('00' + str).substr(str.length))
        }
    }
    return fmt
}

const showMsg = (msg, icon = 'none', duration = 2000) => {
    wx.showToast({
        title: msg || '',
        mask: 'true',
        icon: icon,
        duration: duration
    })
}

const loading = (title, mask) => {
    wx.showLoading({
        title: title || '加载中',
        mask: mask ? mask : true
    })
}

function validateResult(error) {
    if (error && error.message !== '') {
        showMsg(error.message)
        return false
    }
    return true
};

const required = (value, msg = '必填项') => {
    let spacePattern = /^\s+$/;
    let hasSpace = spacePattern.test(value);
    if (value == null || value.length === 0 || hasSpace) {
        return validateResult(new Error(msg))
    }
    return validateResult()
}

const checkPass = (value, confirm, msg = '密码必须由6-18位的数字加字母组成') => {
    var reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/
    let result = reg.test(value)
    if (!result) {
        return validateResult(new Error(msg));
    }
    if (confirm !== '') {
        return checkPassConfirm(value, confirm);
    }

    return validateResult()
}

const checkPassConfirm = (value, confirm, msg = '两次输入密码不一致!') => {
    if (value !== confirm) {
        return validateResult(new Error(msg))
    }
    return validateResult()
}

/**
 * 深拷贝对象
 * @param {Obect} obj 要复制的对象
 */
const deepClone = function(obj) {
    if (Array.isArray(obj)) {
        return obj.map(deepClone)
    } else if (obj && typeof obj === 'object') {
        var cloned = {}
        var keys = Object.keys(obj)
        for (var i = 0, l = keys.length; i < l; i++) {
            var key = keys[i]
            cloned[key] = deepClone(obj[key])
        }
        return cloned
    } else {
        return obj
    }
}

// 生成uuid
const genUuid = function() {
    let s = []
    let hexDigits = '0123456789abcdef'
    for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
    }
    s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = '-'

    let uuid = s.join('')
    return uuid
}

/**
 * 删除storage
 */
function removeSession(key) {
    wx.removeStorageSync(key)
}

/**
 * 存取localStorage
 *
 * @param {any} key
 * @param {any} value
 * @returns
 */
export const session = function(key, value) {
    if (value === void(0)) {
        return wx.getStorageSync(key)
    } else {
        return wx.setStorageSync(key, value)
    }
}

/**
 * 获取当前页面URL参数
 *
 */
const getCurrentPageUrlWithArgs = function() {
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const url = currentPage.route
    const options = currentPage.options
    let urlWithArgs = `/${url}?`
    for (let key in options) {
        const value = options[key]
        urlWithArgs += `${key}=${value}&`
    }
    urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
    return urlWithArgs
}

const getRect = function (vm, selector, all) {
    return new Promise((resolve) => {
        wx.createSelectorQuery()
        .in(vm)
        [all ? 'selectAll' : 'select'](selector)
        .boundingClientRect((rect) => {
            if (all && Array.isArray(rect) && rect.length) {
            resolve(rect);
            }
            if (!all && rect) {
            resolve(rect);
            }
        })
        .exec();
    });
}

const C = {
    // fileBaseUrl: 'http://logistics-miniapp.rx.test.prd.uimpcloud.com' // 测试环境
    // fileBaseUrl: 'https://gateway.runxinlvye.cn:9443/miniappapi' // 生产环境
    // fileBaseUrl: 'https://gateway.runxinlvye.cn/miniappapi' // 生产连VPN的环境
    // fileBaseUrl: 'http://localhost:8081' // 个人环境
    fileBaseUrl: 'http://miniappapi.rx.dev.prd.uimpcloud.com' // 开发环境
}

module.exports = { 
    showMsg,
    loading,
    required,
    checkPass,
    checkPassConfirm,
    formatDate,
    deepClone,
    genUuid,
    session,
    removeSession,
    getCurrentPageUrlWithArgs,
    getRect,
    C
}
